import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import io from 'socket.io-client'
import { getTokenInfo } from '@/utils/storage'

const Chat = () => {
  const listRef = useRef(null)
  const clientRef = useRef(null)
  // 初始的聊天记录
  const [messageList, setMessageList] = useState([
    { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', text: '你好' }
  ])
  // input框的消息
  const [msg, setMsg] = useState('')
  const onKeyUp = (e) => {
    // 判断回车之后 把消息添加到消息列表中
    if (e.keyCode !== 13) return
    if (!msg) return
    setMessageList((messageList) => [
      ...messageList,
      { type: 'user', text: msg }
    ])
    // console.log(messageList);
    // 给服务器发消息
    clientRef.current.emit('message', {
      msg,
      timestamp: Date.now()
    })
    setMsg('')
  }
  // 刚一进来就要建立连接，在useEffect里面
  useEffect(() => {
    clientRef.current = io('http://toutiao.itheima.net', {
      query: {
        token: getTokenInfo().token
      },
      transports: ['websocket']
    })
    // 与服务器建立连接
    clientRef.current.on('connect', () => {
      // console.log('建立连接成功');
      // 建立连接成功之后增加一条消息
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', text: 'hello' }
      ])
    })
    // 服务端给客户端发消息
    clientRef.current.on('message', (e) => {
      // console.log('建立连接成功');
      // 建立连接成功之后增加一条消息
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', text: e.msg }
      ])
    })
    // 组件销毁时要断开连接
    return () => {
      clientRef.current.close()
    }
  }, [])
  useEffect(() => {
    listRef.current.scrollTop = listRef.current.scrollHeight - listRef.current.offsetTop
  }, [messageList])
  const history = useHistory()
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onLeftClick={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={listRef}>
        {/* 机器人的消息 */}
        {
          messageList.map((item, index) => {
            if (item.type === 'robot') {
              return (
                <div className="chat-item" key={index}>
                  <Icon type="iconbtn_xiaozhitongxue" />
                  <div className="message">{item.text}</div>
                </div>
              )
            } else {
              return (
                <div className="chat-item user" key={index}>
                  <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
                  <div className="message">{item.text}</div>
                </div>
              )
            }

          })
        }
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="no-border"
          placeholder="请描述您的问题"
          value={msg}
          onChange={(e) => setMsg(e.target.value)}
          onKeyUp={onKeyUp}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat